<template>
  <el-dialog v-model="dialogVisible" :destroy-on-close="true" :align-center="true" width="30%" :title="`添加企业用户`">
    <el-form
      ref="ruleFormRef"
      :rules="rules"
      :disabled="dialogData.isView"
      :model="dialogData.itemInfo"
      label-width="120px"
      label-suffix=" :"
      :hide-required-asterisk="dialogData.isView"
    >
      <el-row :gutter="20">
        <el-col :span="24">
          <el-row>
            <el-col>
              <el-form-item label="手机号" prop="phone">
                <el-input v-model="dialogData.itemInfo.phone" placeholder="请填写手机号" clearable>
                  <template #prefix>
                  <el-icon class="el-input__icon"><user /></el-icon>
                </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <div class="captcha-frame-wrapper">
              <div class="captcha-frame">
                <el-form-item label="验证码" prop="code">
                  <el-input placeholder="短信验证码" v-model="dialogData.itemInfo.code">
                    <template #prefix>
                      <el-icon class="el-input__icon"><Key /></el-icon>
                    </template>
                  </el-input>
                </el-form-item>
              </div>
              <div class="captcha-box">
                <el-button style="width: 100%" type="primary" :loading-icon="Eleme" :loading="!canClick" @click="handleSendCode">{{
                  buttonCtn
                }}</el-button>
              </div>
            </div>
          </el-row>
          <el-row v-if="dialogData.optType === OptEnum.CREATE">
            <el-col>
              <el-form-item label="密码" prop="password">
                <el-input
                  type="password"
                  show-password
                  v-model="dialogData.itemInfo.password"
                  placeholder="请填写密码"
                  clearable
                >
                <template #prefix>
                  <el-icon class="el-input__icon"><Lock /></el-icon>
                </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" v-show="!dialogData.isView" @click="handleSubmit" :loading="btnLoading">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { getOptTitle, OptEnum, sysEnum } from "@/biz/eenum/appEnum";
import { DialogParam } from "@/biz/interface/DialogType";
import { CompanyUserEntity } from "@/biz/interface/CompanyType";
import { getUserInfoApi } from "@/api/modules/sys/user";
import md5 from "md5";
import { saveCompanyUserByPhoneApi } from "@/api/modules/cpy/act";
import { UserInfoEntity } from "@/biz/interface/userType";
import { Eleme } from "@element-plus/icons-vue";
import { bizPhoneCode } from "@/biz/modules/user";
import { vaildPhoneNumber } from "@/utils/check";

const rules = reactive({
  phone: [{ required: true, message: "请填写手机号", trigger: "blur" }],
  code: [{ required: true, message: "请填写验证码", trigger: "blur" }],
  password: [{ required: true, message: "请填写密码", trigger: "blur" }]
});

//页面的数据
interface UserDialogOption extends DialogParam {
  //弹出表单的标题
  title: string;
  //是否是查看状态，查看状态是不可以提交数据  isView: false,
  isView: boolean;
  //是否是审核状态
  isAudit: boolean;
  //当前的数据对象
  itemInfo: UserInfoEntity;
}

//按钮是否可点
const canClick = ref(true);
const totalTime = ref(60);
const buttonCtn = ref("发送短信验证码");

//提交按钮，避免多次提交
const btnLoading = ref(false);
// 弹出框的参数
const dialogVisible = ref(false);
const dialogData = reactive<UserDialogOption>({
  optType: OptEnum.UNKNOW,
  title: "",
  isView: false,
  isAudit: false,
  itemInfo: {
    account: "",
    password: "",
    name: "",
    gender: sysEnum.ONE,
    phone: "",
    idCard: "",
    email: "",
    avator: "",
    auditContent: ""
  }
});

// 接收父组件传过来的参数
const acceptParams = (params: DialogParam): void => {
  dialogData.optType = params.optType;
  dialogData.rowData = params.rowData;

  dialogData.isView = dialogData.optType === OptEnum.VIEW;
  dialogData.isAudit = dialogData.optType === OptEnum.AUDIT;
  dialogData.title = getOptTitle(dialogData.optType);

  if (dialogData.optType === OptEnum.CREATE) {
    initItemInfo();
  } else if (dialogData.rowData && dialogData.rowData.id) {
    getItemInfo(dialogData.rowData.id);
  }

  dialogVisible.value = true;
};

const initItemInfo = (): void => {
  dialogData.itemInfo = {
    account: "",
    password: "",
    name: "",
    gender: sysEnum.ONE,
    phone: "",
    idCard: "",
    email: "",
    avator: "",
    auditContent: ""
  };
};

//获取当前数据的详情，不通过表格上的数据行，直接调用接口获取数据
const getItemInfo = async (id: string) => {
  if (id) {
    //通过接口获取数据
    let { data } = await getUserInfoApi({ id });
    // console.log("接收到服务器端的数据", data);
    dialogData.itemInfo = data as unknown as CompanyUserEntity;
  }
};

// 获取验证码
const getPhoneCode = () => {
  bizPhoneCode(dialogData.itemInfo.phone)
    .then(res => {
      if (res.data) {
        ElMessage.error("验证码已发送.");
      }
    })
    .catch(err => {
      console.log(err);
    });
};

//发送验证码
const handleSendCode = () => {
  if (!canClick.value) {
    return;
  }

  if (!dialogData.itemInfo.phone) {
    ElMessage.error("请输入接收验证码的手机号.");
    return;
  }

  if (!vaildPhoneNumber(dialogData.itemInfo.phone)) {
    ElMessage.error("请输入正确的手机号.");
    return;
  }

  //调用手机短信功能
  getPhoneCode();

  canClick.value = false;
  let clock = window.setInterval(() => {
    totalTime.value = totalTime.value - 1;
    buttonCtn.value = totalTime.value + " 秒后可重新发送";
    if (totalTime.value < 0) {
      window.clearInterval(clock);
      buttonCtn.value = " 重新发送验证码";
      totalTime.value = 60;
      canClick.value = true;
    }
  }, 1000);
};

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  btnLoading.value = true;
  ruleFormRef.value!.validate(async valid => {
    if (!valid) {
      btnLoading.value = false;
      return;
    }
    try {
      if (dialogData.optType === OptEnum.CREATE || dialogData.optType === OptEnum.EDIT) {
        //提交数据
        let res = await saveCompanyUserByPhoneApi({
          ...dialogData.itemInfo,
          password: md5(dialogData.itemInfo.password)
        });
        if (res.data) {
          //去创建一个企业的可配置币的帐号
          // saveCompanyUserConfigApi(res.data as string);
          ElMessage.success({ message: `${dialogData.title}用户成功！` });
          //刷新列表数据
          emits("refresh-list");
          dialogVisible.value = false;
        }
      }
    } catch (error) {
      // console.log(error);
    } finally {
      btnLoading.value = false;
    }
  });
};

// // 公共校验方法（图片上传成功触发重新校验）
// const checkValidate = (val: string) => {
//   ruleFormRef.value!.validateField(val, () => {});
// };

//页面事件
const emits = defineEmits(["refresh-list"]);

//页面参数
defineExpose({
  acceptParams
});
</script>

<style lang="scss" scoped>

.captcha-frame-wrapper {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;

  .captcha-frame {
    width: 58%;
  }
  .captcha-box {
    width: 38%;
    height: 2.5rem;
    cursor: pointer;
    & img {
      width: 100%;
      height: 100%;
    }
  }
}
</style>
